<template>
    <basic-container>
        <avue-crud :option="option"
                   :table-loading="loading"
                   :data="data"
                   v-model:page="page"
                   v-model:search="search"
                   :permission="permissionList"
                   :before-open="beforeOpen"
                   v-model="form"
                   ref="crud"
                   @row-update="rowUpdate"
                   @row-save="rowSave"
                   @row-del="rowDel"
                   @search-change="searchChange"
                   @sort-change="sortChange"
                   @search-reset="searchReset"
                   @selection-change="selectionChange"
                   @current-change="currentChange"
                   @size-change="sizeChange"
                   @refresh-change="refreshChange"
                   @on-load="onLoad"
                   :summary-method="summaryMethod">
            <template #menu-left>
                <el-button
                        type="warning"
                        icon="el-icon-download"
                        @click="handleExport"
                >导出
                </el-button>
            </template>

          <template #invoiceDate-search="{ disabled, size }">
            <el-date-picker
                size="default"
                style="width:94%"
                v-model="this.invoiceDateRange"
                type="daterange"
                :format="dateFormat"
                :value-format="dateFormat"
                unlink-panels
                start-placeholder="Start Date"
                end-placeholder="End Date"
                clearable
                placeholder="发票日期"
                @change="handleDateChange"
                :picker-options="pickerOptions"
            >
            </el-date-picker>
          </template>

          <template #asnDate-search="{ disabled, size }">
            <el-date-picker
                size="default"
                style="width:94%"
                v-model="this.asnDateRange"
                type="daterange"
                :format="dateFormat"
                :value-format="dateFormat"
                unlink-panels
                start-placeholder="Start Date"
                end-placeholder="End Date"
                clearable
                placeholder="ASN日期"
                @change="handleAsnDateChange"
                :picker-options="pickerOptions"
            >
            </el-date-picker>
          </template>

        </avue-crud>
    </basic-container>
</template>

<script>
    import {selectInvoiceDetails} from "@/api/anwise/invoice/invoice_item";
    import {mapGetters} from "vuex";
    import { getToken } from '@/utils/auth';
    import { exportBlob } from '@/api/common';
    import { downloadXls } from '@/utils/util';
    import NProgress from 'nprogress';
    import 'nprogress/nprogress.css';
    import {selectCustomerGroup} from "@/api/anwise/material/customer_group";

    export default {
        data() {
            return {
                form: {},
                query: {},
                search:{},
                invoiceDateRange:[],
              asnDateRange:[],
                loading: true,
                page: {
                    pageSize: 20,
                    currentPage: 1,
                    total: 0
                },
                selectionList: [],
                dateFormat: 'YYYY-MM-DD',
                pickerOptions: {},
                programCodeSelect:[],
                option: {
                    height:'auto',
                    calcHeight: 30,
                    tip: false,
                    searchShow: false,
                    searchMenuSpan: 6,
                    border: true,
                    index: true,
                    selection: false,
                    reserveSelection:true,
                    labelWidth: 150,
                    indexWidth:100,
                    menuWidth: 100,
                    addBtn: false,
                    editBtn: false,
                    viewBtn: false,
                    delBtn: false,
                    stripe: true,
                    searchIndex: 3,
                    searchIcon: false,
                    searchLabelWidth:140,
                    searchEnter:true,
                    showSummary: true,
                    menu:false,
                    column: [
                      {
                        label: "发票号",
                        prop: "invNo",
                        type: "input",
                        search: true,
                        fixed: true,
                        overHidden: true,
                        sortable: true,
                        width:140,
                      },
                      {
                        label: "发票日期",
                        prop: "invoiceDate",
                        type: "date",
                        search: true,
                        fixed: true,
                        overHidden: true,
                        sortable: true,
                        width:140,
                        valueFormat: 'YYYY-MM-DD',
                        format:'YYYY-MM-DD',
                      },
                      {
                        label: "ASN编号",
                        prop: "asnNo",
                        type: "input",
                        search: true,
                        overHidden: true,
                        sortable: true,
                        width:140,
                        rules: [{
                          required: true,
                          message: "请输入ASN编号",
                          trigger: "blur"
                        }],
                      },
                      {
                        label: "ASN项",
                        prop: "asnItem",
                        type: "input",
                        overHidden: true,
                        sortable: true,
                        width:140,
                      },
                      {
                        label: "ASN日期",
                        prop: "asnDate",
                        type: "date",
                        search: true,
                        overHidden: true,
                        sortable: true,
                        width:140,
                        valueFormat: 'YYYY-MM-DD',
                        format:'YYYY-MM-DD',
                      },
                      {
                        label: "订单号码",
                        prop: "orderNo",
                        type: "input",
                        search: true,
                        overHidden: true,
                        sortable: true,
                        width:140,
                        rules: [{
                          required: true,
                          message: "请输入订单编号",
                          trigger: "blur"
                        }],
                      },
                      {
                        label: "出仓单号",
                        prop: "outNo",
                        type: "input",
                        search: true,
                        overHidden: true,
                        sortable: true,
                        width:140,
                        rules: [{
                          required: true,
                          message: "请输入出仓单号",
                          trigger: "blur"
                        }],
                      },
                      {
                        label: "出仓日期",
                        prop: "outDate",
                        type: "date",
                        overHidden: true,
                        sortable: true,
                        width:140,
                        valueFormat: 'YYYY-MM-DD',
                        format:'YYYY-MM-DD',
                      },
                      {
                        label: "客户PO",
                        prop: "poNo",
                        type: "input",
                        overHidden: true,
                        sortable: true,
                        width:140,
                      },
                      {
                        label: "收款方",
                        prop: "companyName",
                        type: "input",
                        search: true,
                        overHidden: true,
                        sortable: true,
                        width:140,
                        rules: [{
                          required: true,
                          message: "请输入收款方",
                          trigger: "blur"
                        }],
                      },
                      {
                        label: "客户账号",
                        prop: "customerNo",
                        type: "input",
                        search: true,
                        overHidden: true,
                        sortable: true,
                        width:140,
                        rules: [{
                          required: true,
                          message: "请输入客户账号",
                          trigger: "blur"
                        }],
                      },
                      {
                        label: "客户名称",
                        prop: "customerName",
                        type: "input",
                        search: true,
                        overHidden: true,
                        sortable: true,
                        width:140,
                        rules: [{
                          required: true,
                          message: "请输入客户名称",
                          trigger: "blur"
                        }],
                      },
                      {
                        label: "物料编号",
                        prop: "materialNo",
                        type: "input",
                        overHidden: true,
                        sortable: true,
                        width:140,
                      },
                      {
                        label: "物料名称",
                        prop: "materialName",
                        type: "input",
                        search: true,
                        overHidden: true,
                        sortable: true,
                        width:140,
                        rules: [{
                          required: true,
                          message: "请输入物料名称",
                          trigger: "blur"
                        }],
                      },
                      {
                        label: "客户条码",
                        prop: "barCode",
                        type: "input",
                        search: true,
                        overHidden: true,
                        sortable: true,
                        width:140,
                        rules: [{
                          required: true,
                          message: "请输入客户条码",
                          trigger: "blur"
                        }],
                      },
                      {
                        label: "产品描述",
                        prop: "description",
                        type: "input",
                        overHidden: true,
                        sortable: true,
                        width:140,
                      },
                      {
                        label: "数量",
                        prop: "deliNum",
                        type: "input",
                        overHidden: true,
                        sortable: true,
                        width:140,
                      },
                      {
                        label: "币别",
                        prop: "currency",
                        type: "select",
                        filterable: true,
                        overHidden: true,
                        sortable: true,
                        search: true,
                        width:120,
                        dicUrl: '/api/blade-system/dict-biz/dictionary?code=rmb',
                        props: {
                          label: 'dictValue',
                          value: 'dictKey',
                        },
                        dataType: 'string',
                      },
                      {
                        label: "单价/100PCS",
                        prop: "checkPriceNum",
                        type: "input",
                        overHidden: true,
                        sortable: true,
                        width:140,
                      },
                      {
                        label: "金额",
                        prop: "checkTotalPrice",
                        type: "input",
                        overHidden: true,
                        sortable: true,
                        width:140,
                      },
                      {
                        label: "箱数",
                        prop: "ctnNum",
                        type: "input",
                        overHidden: true,
                        sortable: true,
                        width:140,
                      },
                      {
                        label: "CBM",
                        prop: "totalCbm",
                        type: "input",
                        overHidden: true,
                        sortable: true,
                        width:140,
                      },
                      {
                        label: "收货工厂",
                        prop: "factoryName",
                        type: "input",
                        search: true,
                        overHidden: true,
                        sortable: true,
                        width:140,
                        rules: [{
                          required: true,
                          message: "请输入收货工厂",
                          trigger: "blur"
                        }],
                      },
                      {
                        label: "业务人员",
                        prop: "serviceName",
                        type: "input",
                        overHidden: true,
                        sortable: true,
                        width:140,
                      },
                      {
                        label: "品牌分组",
                        prop: "programGroup",
                        type: "input",
                        overHidden: true,
                        sortable: true,
                        width:140,
                      },
                      {
                        label: "品牌",
                        prop: "programName",
                        type:"select",
                        filterable:true,
                        dicUrl: '/api/blade-anwise/customer_group/select',
                        props: {
                          label: 'programName',
                          value: 'programName',
                        },
                        dataType: 'string',
                        rules: [{
                          required: false,
                          message: "请选择品牌",
                          trigger: "blur"
                        }],
                        search: true,
                        overHidden: true,
                        sortable: true,
                        width:120,
                      },
                      {
                        label: "发票状态",
                        prop: "invoiceStatus",
                        type: "select",
                        filterable: true,
                        overHidden: true,
                        sortable: true,
                        search: true,
                        width:120,
                        dicUrl: '/api/blade-system/dict-biz/dictionary?code=invoice_status',
                        props: {
                          label: 'dictValue',
                          value: 'dictKey',
                        },
                        dataType: 'string',
                      },
                      {
                        label: "Posted",
                        prop: "billCheck",
                        type: "select",
                        search: true,
                        dicUrl: "/blade-system/dict-biz/dictionary?code=biz_yes_no",
                        filterable: true,
                        props: {
                          label: 'dictValue',
                          value: 'dictKey',
                        },
                        value:'是',
                        dataType: 'string',
                        overHidden: true,
                        sortable: true,
                        width:140,
                      },
                    ]
                },
                data: []
            };
        },
        computed: {
            ...mapGetters(["permission"]),
            permissionList() {
                return {
                    checkPriceBtn: this.validData(this.permission.order_check_price, false),
                    viewBtn: this.validData(this.permission.order_details_view, false),
                };
            },
            ids() {
                let ids = [];
                this.selectionList.forEach(ele => {
                    ids.push(ele.id);
                });
                return ids.join(",");
            }
        },
        mounted() {
          this.$nextTick(() => {
            this.selectDicData();
          })
        },
        methods: {
            selectDicData() {
              // selectCustomerGroup().then(res => {
              //   this.programCodeSelect = res.data.data;
              //   let dicList=[];
              //   this.programCodeSelect.forEach(res=>{
              //     let dic={};
              //     dic.label = res.programName;
              //     dic.value = res.programName;
              //     dicList.push(dic);
              //   })
              //   const column =  this.findObject(this.option.column, 'programName');
              //   console.log(dicList)
              //   column.dicData = dicList;
              // })
            },
            handleExport(){
                NProgress.start();
                this.query.checkPrice = this.permission.invoice_check_price;
                exportBlob(
                    `/blade-anwise/invoice/invoice_item/export?${this.website.tokenHeader
                    }=${getToken()}`, this.query
                ).then(res => {
                    downloadXls(res.data, `发票明细${this.$dayjs().format('YYYYMMDDHHmmss')}.xlsx`);
                    NProgress.done();
                });
            },
            rowSave(row, done, loading) {
                add(row).then(() => {
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                    done();
                }, error => {
                    loading();
                    window.console.log(error);
                });
            },
            rowUpdate(row, index, done, loading) {
                update(row).then(() => {
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                    done();
                }, error => {
                    loading();
                    window.console.log(error);
                });
            },
            rowDel(row) {
                this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        return remove(row.id);
                    })
                    .then(() => {
                        this.onLoad(this.page);
                        this.$message({
                            type: "success",
                            message: "操作成功!"
                        });
                    });
            },
            handleDelete() {
                if (this.selectionList.length === 0) {
                    this.$message.warning("请选择至少一条数据");
                    return;
                }
                this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        return remove(this.ids);
                    })
                    .then(() => {
                        this.onLoad(this.page);
                        this.$message({
                            type: "success",
                            message: "操作成功!"
                        });
                        this.$refs.crud.toggleSelection();
                    });
            },
            summaryMethod ({ columns, data }) {
                const sums = [];
                if (columns.length > 0) {
                    sums[0] = '合计：';
                    columns.forEach((column, index) => {
                        let prop = column.property
                        if (['deliNum','checkTotalPrice','ctnNum','cbm'].includes(prop)) {
                            let values = data.map(item => Number(item[prop] || 0));
                            let all = values.length !== 0 ? sums[index] = values.reduce((a, b) => {
                                return a + b;
                            }) : 0
                            if (['deliNum','ctnNum'].includes(prop)) {
                                sums[index] = this.$toFixed(all,0)
                            }
                            if(['checkTotalPrice','cbm'].includes(prop)) {
                                sums[index] = this.$toFixed(all,2)
                            }
                        }
                    });
                }
                return sums;
            },
            beforeOpen(done, type) {
                if (["edit", "view"].includes(type)) {
                    getDetail(this.form.id).then(res => {
                        this.form = res.data.data;
                    });
                }
                done();
            },
            searchReset() {
                this.query = {};
              this.invoiceDateRange = [];
              this.asnDateRange = [];
              this.search.invoiceDateStart = '';
              this.search.invoiceDateEnd = '';
              this.search.asnDateStart = '';
              this.search.asnDateEnd = '';
                this.onLoad(this.page);
            },
            searchChange(params, done) {
                this.query = params;
                // Object.assign(this.query, params)
                this.page.currentPage = 1
                this.onLoad(this.page, params);
                done();
            },
          sortChange(val) {
            console.log(val)
            this.sort = {
              prop: val.prop,
              order: val.order
            };
            this.query.descs = '';
            this.query.ascs = '';
            if (this.sort.prop && this.sort.order) {
              if (this.sort.order === "descending") {
                this.query.descs = this.sort.prop;
              } else {
                this.query.ascs = this.sort.prop;
              }
            }
            this.onLoad(this.page);
          },
            selectionChange(list) {
                this.selectionList = list;
            },
            selectionClear() {
                this.selectionList = [];
                this.$refs.crud.toggleSelection();
            },
            currentChange(currentPage){
                this.page.currentPage = currentPage;
            },
            sizeChange(pageSize){
                this.page.pageSize = pageSize;
            },
            refreshChange() {
                this.onLoad(this.page, this.query);
            },
            onLoad(page, params = {}) {
                this.loading = true;
                // console.log(this.permissionList.checkPriceBtn)
                params.checkPrice = this.permission.invoice_check_price;
              selectInvoiceDetails(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
                    const data = res.data.data;
                    this.page.total = data.total;
                    this.data = data.records;
                    this.loading = false;
                    this.selectionClear();
                });
            },
          handleDateChange(value) {
            if (value) {
              this.search.invoiceDateStart = value[0];
              this.search.invoiceDateEnd = value[1];
            } else {
              this.search.invoiceDateStart = '';
              this.search.invoiceDateEnd = '';
            }
          },
          handleAsnDateChange(value) {
            if (value) {
              this.search.asnDateStart = value[0];
              this.search.asnDateEnd = value[1];
            } else {
              this.search.asnDateStart = '';
              this.search.asnDateEnd = '';
            }
          }
        }
    };
</script>

<style>
    .row-yellow {
        background-color: rgb(255, 253, 230) !important;
        cursor: pointer;
    }

    input::-webkit-outer-spin-button,
    input::-webkit-inner-spin-button{
        -webkit-appearance: none !important;
        margin: 0;
    }
</style>
